package com.minisoft.workhour.service;

import com.minisoft.workhour.client.ManhourApiClient;
import com.minisoft.workhour.model.ManhourRequest;
import com.minisoft.workhour.model.WorkItem;
import com.minisoft.workhour.parser.WeeklyReportParser;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 工时服务类
 */
@Slf4j
public class WorkhourService {
    
    private final WeeklyReportParser parser;
    private final ManhourApiClient apiClient;
    
    public WorkhourService() {
        this.parser = new WeeklyReportParser();
        this.apiClient = new ManhourApiClient();
    }
    
    /**
     * 处理周报Excel文件并提交工时
     */
    public void processWeeklyReport(String excelFilePath) {
        try {
            log.info("开始处理周报文件: {}", excelFilePath);
            
            // 1. 解析Excel文件
            List<WorkItem> workItems = parser.parseExcel(excelFilePath);
            
            if (workItems.isEmpty()) {
                log.warn("没有解析到任何工作项");
                return;
            }
            
            log.info("解析到 {} 个工作项", workItems.size());
            
            // 2. 打印解析结果
            printWorkItems(workItems);
            
            // 3. 转换为API请求格式
            List<ManhourRequest.ManhourItem> manhourItems = workItems.stream()
                    .map(ManhourRequest.ManhourItem::fromWorkItem)
                    .collect(Collectors.toList());
            
            ManhourRequest request = new ManhourRequest(manhourItems);
            
            // 4. 提交工时记录
            log.info("开始提交工时记录...");
            int successCount = apiClient.batchSubmitManhour(request);
            
            log.info("工时处理完成，成功提交: {}/{}", successCount, workItems.size());
            
        } catch (IOException e) {
            log.error("处理Excel文件时发生异常: {}", excelFilePath, e);
        } catch (Exception e) {
            log.error("处理周报时发生未知异常", e);
        }
    }
    
    /**
     * 仅解析Excel文件，不提交工时
     */
    public List<WorkItem> parseOnly(String excelFilePath) {
        try {
            log.info("解析周报文件: {}", excelFilePath);
            List<WorkItem> workItems = parser.parseExcel(excelFilePath);
            
            log.info("解析到 {} 个工作项", workItems.size());
            printWorkItems(workItems);
            
            return workItems;
            
        } catch (IOException e) {
            log.error("解析Excel文件时发生异常: {}", excelFilePath, e);
            return java.util.Collections.emptyList();
        }
    }
    
    /**
     * 提交指定的工作项
     */
    public int submitWorkItems(List<WorkItem> workItems) {
        if (workItems.isEmpty()) {
            log.warn("没有工作项需要提交");
            return 0;
        }
        
        List<ManhourRequest.ManhourItem> manhourItems = workItems.stream()
                .map(ManhourRequest.ManhourItem::fromWorkItem)
                .collect(Collectors.toList());
        
        ManhourRequest request = new ManhourRequest(manhourItems);
        
        log.info("开始提交 {} 个工时记录...", workItems.size());
        return apiClient.batchSubmitManhour(request);
    }
    
    /**
     * 打印工作项列表
     */
    private void printWorkItems(List<WorkItem> workItems) {
        log.info("=== 解析结果 ===");

        // 统计工作天数
        long workDays = workItems.stream()
                .map(WorkItem::getWorkDate)
                .distinct()
                .count();

        // 统计总工时
        double totalHours = workItems.stream()
                .mapToDouble(WorkItem::getHours)
                .sum();
        for (int i = 0; i < workItems.size(); i++) {
            WorkItem item = workItems.get(i);
            log.info("{}. {} | {}小时 | {} | {}",
                    i + 1,
                    item.getDescription(),
                    item.getHours(),
                    item.getTaskId(),
                    item.getWorkDate());
        }
        log.info("工作天数: {} 天, 总工时: {} 小时, 工作项数量: {} 个",
                workDays, totalHours, workItems.size());
        log.info("----------------------------------------");
        log.info("=== 解析结果结束 ===");
    }
}
